package com.zhubayi.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.zhubayi.entity.Category;
import com.zhubayi.entity.R;
import com.zhubayi.entity.User;
import com.zhubayi.entity.Video;
import com.zhubayi.entity.vo.UpdateAddVideoVo;
import com.zhubayi.entity.vo.VideoVo;
import com.zhubayi.mapper.CategoryMapper;
import com.zhubayi.service.HistoryService;
import com.zhubayi.service.UserService;
import com.zhubayi.service.VideoService;
import com.zhubayi.utils.FileUtils;
import com.zhubayi.utils.VideoQueryConditionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 祝八一
 */
@Controller
@RequestMapping("video")
public class VideoController {
    @Autowired
    private VideoService videoService;
    @Autowired
    private UserService userService;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private HistoryService historyService;
    @GetMapping("tolist")
    public String tolist(VideoQueryConditionUtils utils,Model model,@RequestParam(required = false) Integer currentPage,String time,@RequestParam(required = false)Integer pageSize){
        if (currentPage==null||currentPage<0){
            currentPage=1;
        }
        if (pageSize==null){
            pageSize=5;
        }
        if (time!=null&&!"".equals(time)){
             utils.setStartTime(time.substring(0,10));
             utils.setEndTime(time.substring(13));
             utils.setTime(time);
        }
       // System.out.println(utils+"================");
        //只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
        //开启分页
        PageHelper.startPage(currentPage, pageSize).setOrderBy("vid desc");
       // List<VideoVo> videoVoList = videoService.getAll();
        List<VideoVo> videoVoList=videoService.queryCondition(utils);
        PageInfo<VideoVo> pageInfo = new PageInfo<>(videoVoList);
        model.addAttribute("queryCondition",new VideoQueryConditionUtils());
        model.addAttribute("videosPage" ,pageInfo);
        model.addAttribute("queryCondition",utils);
        model.addAttribute("categories" ,categoryMapper.queryAll());
       return "admin/video_list";
    }
    @GetMapping("search")
    public String search(String time,VideoQueryConditionUtils utils,@RequestParam Integer currentPage,@RequestParam Integer pageSize,Model model){
        if (currentPage==null||currentPage<0){
            currentPage=1;
        }
        if (pageSize==null){
            pageSize=5;
        }
        if (time!=null&&!"".equals(time)){
            utils.setStartTime(time.substring(0,10));
            utils.setEndTime(time.substring(13));
        }

        //只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
        PageHelper.startPage(currentPage, pageSize);//.setOrderBy("vid desc");
        List<VideoVo> videoVo=videoService.queryCondition(utils);
        PageInfo<VideoVo> pageInfo = new PageInfo<>(videoVo);
        if (pageInfo.getPages()==0){
            pageInfo.setPages(1);
        }
        model.addAttribute("categories" ,categoryMapper.queryAll());
        model.addAttribute("queryCondition",utils);
        model.addAttribute("videosPage" ,pageInfo);
        return "admin/video_list";

    }
    @ResponseBody
    @GetMapping("del/{id}")
    public boolean del(@PathVariable("id") Integer id){
        Video video = videoService.queryById(id);
        if (video!=null){
            if (video.getUrl()!=null&&!"".equals(video.getUrl())){
                //删除视频文件
                String[] str = video.getUrl().split("/");
                //删除文件
                new File("D://test//uploadFile/video/"+str[str.length-1]).delete();
            }
            //删除图片文件
            if (video.getCover()!=null&&!"".equals(video.getCover())){
                //删除视频文件
                String[] str = video.getCover().split("/");
                //删除文件
                new File("D://test//uploadFile/images/"+str[str.length-1]).delete();
            }
        }
        videoService.deleteById(id);
        return true;
    }
    @RequestMapping("toupdate/{id}")
    public String update(@PathVariable("id")Integer id, Model model){
        Video video = videoService.queryById(id);
        if (video==null){
            return "redirect:/video/tolist";
        }
        model.addAttribute("video",video);
        model.addAttribute("categories" ,categoryMapper.queryAll());
        return "admin/updateVideo";
    }
    @Transactional
    @GetMapping("view/{id}")
    public String view(HttpServletRequest request,@PathVariable("id") Integer id,Model model){
        videoService.addViewNum(id);
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user!=null){
            //登录了
            historyService.add(user.getId(),id);
        }
        model.addAttribute("video",videoService.queryById(id));
        return "view";

    }
    @PostMapping("updateOrAdd")
    public String updateOrAdd(UpdateAddVideoVo vo) throws IOException {

        if (vo.getCategoryId()!=null&&vo.getId()!=null&&vo.getName()!=null&&vo.getStatus()!=null){
            Video video = videoService.queryById(vo.getId());
            video.setTitle(vo.getName());
            video.setCategoryId(vo.getCategoryId());
            video.setStatus(vo.getStatus());
            if (!vo.getVideoCover().isEmpty()){
                if (video.getCover()!=null){
                    String[] str = video.getCover().split("/");
                    //删除文件
                    new File("D://test//uploadFile/images/"+str[str.length-1]).delete();
                }
                String url = FileUtils.uploadFile("images", vo.getVideoCover());
                video.setCover("http://127.0.0.1:8080/uploadFile/images/"+url);
            }
            if (!vo.getVideoFile().isEmpty()){
                if (video.getUrl()!=null){
                    String[] str = video.getUrl().split("/");
                    //删除文件
                    new File("D://test//uploadFile/video/"+str[str.length-1]).delete();
                }
                String url = FileUtils.uploadFile("video", vo.getVideoFile());
                video.setUrl("http://127.0.0.1:8080/uploadFile/video/"+url);
            }
            videoService.update(video);
        }

        return "redirect:/video/tolist";
    }
    @Transactional
    @PostMapping("addVideo")
    public String toaddVideo(HttpServletRequest request,UpdateAddVideoVo vo) throws IOException {
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return "redirect:/toLogin";
        }
        Video video = new Video();

        video.setTitle(vo.getName());
        video.setPraiseNum(0);
        video.setPubTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        video.setUserId(user.getId());
        video.setStatus(false);
        video.setGreatNum(0);
        video.setViewNum(0);
        if (vo.getCategoryId()==null||"".equals(vo.getCategoryId())){
            //默认分类
            video.setCategoryId(1);
        }else {
            video.setCategoryId(vo.getCategoryId());
        }
        if (vo.getVideoCover().isEmpty()){
            //设置默认封面
            video.setCover("http://127.0.0.1:8080/uploadFile/images/d2882e6a7ac14d16b47e8d5ebf99a71a.jpg");
        }else {
            String url = FileUtils.uploadFile("images", vo.getVideoCover());
            video.setCover("http://127.0.0.1:8080/uploadFile/images/"+url);
        }
        if (vo.getVideoFile().isEmpty()){
            //重定向到首页
            return "redirect:/";
        }else {
            String url = FileUtils.uploadFile("video", vo.getVideoFile());
            video.setUrl("http://127.0.0.1:8080/uploadFile/video/"+url);
        }
        videoService.add(video);
        //视频数量加1
        userService.addVideoNum(user.getId());

        return "redirect:/";
    }
    @RequestMapping("toaddVideo")
    public String toaddVideo(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return "redirect:/toLogin";
        }
        List<Category> categories = categoryMapper.queryAll();
        model.addAttribute("categories",categories);
        model.addAttribute("type","pubVideo");
        return "video_update";
    }

    public static void main(String[] args) {
        String str="http://127.0.0.1:8080/uploadFile/images05da46ea374b4af596cbcf697e119081.jpg";
        String[] split = str.split("/");
        for (int i = 0; i < split.length; i++) {

            System.out.println(split[split.length-1]);
        }
//        File file = new File("D://test//uploadFile/images/05da46ea374b4af596cbcf697e119081.jpg");
//        System.out.println(file.delete());
//        String str="2021011320210114";
//        String str2="2021-01-09 - 2021-01-16";
//        System.out.println(str2.substring(0,10));
//        System.out.println(str2.substring(13));
    }

}
